from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.decorators import api_view
import json
from django.core import serializers
import logging
import re
import math

logger = logging.getLogger('log')
from ..models import ptTestGrouping,ptTestRequest
from ..serverEvCfg import httpResponseSignal

@csrf_exempt  # 此接口允许跨域访问
@api_view(['POST'])
def addGroup(request):
    '''
    添加分组
    '''
    print(request.body)
    data = eval(json.loads(request.body)["data"])
    try: # 成功
        if (data["name"] != None and len(data) == 3 and data["groupid"] != ""):
            project = ptTestGrouping(group_name=data["name"], group_pj_id=data["groupid"], remark=data["remark"])
            project.save()
            response = httpResponseSignal.httpResponseSignal().getSuccess()
            return JsonResponse(response)
        else: # 错误 缺少必要参数
            response = httpResponseSignal.httpResponseSignal().getFail()
            response["msg"]= "缺少必要参数,请检查"
            return JsonResponse(response)
    except EOFError as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)

@csrf_exempt  # 此接口允许跨域访问
@api_view(['POST'])
def getGroup(request):
    '''
    获取分组信息
    '''
    data = eval(json.loads(request.body)["data"])
    pageSize = data["pageSize"]
    pageNum = data["pageNum"]
    try: # 成功
        group_list = ptTestGrouping.objects.filter(group_pj_id=data["groupid"]).order_by("-updata_time")
        group_size_list = group_list[:pageSize*pageNum] # 查询数据
        group_count = group_list.count() # 查询数据总数量
        all_page_count = math.ceil(group_count/pageSize) # 总页数
        data = json.loads(serializers.serialize("json",group_size_list))[pageSize * pageNum - pageSize:pageSize * pageNum]
        for i in range(len(data)):
            createTime = data[i]["fields"]["creat_time"]
            updataTime = data[i]["fields"]["updata_time"]
            data[i]["fields"]["creat_time"] = re.split('[TZ.]', createTime)[0] + " " + re.split('[TZ.]', createTime)[1]
            data[i]["fields"]["updata_time"] = re.split('[TZ.]', updataTime)[0] + " " + re.split('[TZ.]', updataTime)[1]
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = data
        response["countNum"] = all_page_count  # 总页数
        response["gourpCount"] = group_count  # 总数据量
        response["pageNum"] = pageNum  # 当前页码
        response["pageSize"] = pageSize  # 当前一页多少个数据
        return  JsonResponse(response)
    except EOFError as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)

@csrf_exempt  # 此接口允许跨域访问
@api_view(['POST'])
def updateGroup(request):
    '''
    更新分组信息
    '''
    data = eval(json.loads(request.body)["data"])
    try: # 成功
        if data["id"] !="" and data["name"] !="":
            group = ptTestGrouping.objects.get(group_id=data["id"])
            print("更新分组信息")
            group.group_name = data["name"]
            group.remark = data["remark"]
            group.save()
            response = httpResponseSignal.httpResponseSignal().getSuccess()
            return  JsonResponse(response)

        else: # 错误 缺少必要参数
            response = httpResponseSignal.httpResponseSignal().getFail()
            response["msg"]= "缺少必要参数,请检查"
            return JsonResponse(response)

    except EOFError as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)


@csrf_exempt  # 此接口允许跨域访问
@api_view(['POST'])
def deleteGroup(request):
    '''
    删除分组信息
    '''
    data = eval(json.loads(request.body)["data"])
    try:  # 成功
        if data["id"] != "":
            # 查看其他地方是否使用该分组ID
            group = ptTestRequest.objects.filter(request_group_id=data["id"])
            # 使用中
            if len(group) > 0:
                response = httpResponseSignal.httpResponseSignal().getFail()
                response["msg"] = "该分组ID正常使用中"
                return JsonResponse(response)
            # 没使用 正常删除
            if len(group) == 0:
                ptTestGrouping.objects.filter(group_id=data["id"]).delete()
                response = httpResponseSignal.httpResponseSignal().getSuccess()
                response["msg"] = "删除成功"
                return JsonResponse(response)

        else:  # 错误 缺少必要参数
            response = httpResponseSignal.httpResponseSignal().getFail()
            response["msg"] = "缺少必要参数,请检查"
            return JsonResponse(response)

    except EOFError as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)